import axios from "axios";
import router from "../router";
import { Notification, MessageBox } from "element-ui";

import asc from "@utils/asc.js";

axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
// axios.defaults.headers = "application/json;charset=UTF-8";
axios.defaults.timeout = 10000;

let tokenLoseFlag = false; //目的：token只报错一次

// 请求拦截
axios.interceptors.request.use(
  (config) => {
    // console.log(config,"config")
    const currentUrl = config.url;
    if (
      currentUrl !== "/user/login" &&
      currentUrl !== "/imageCode/getImageCode" &&
      currentUrl !== "/user/forgot" &&
      currentUrl !== "/smsCode/smsScene" &&
      currentUrl !== "/smsCode/getSmsCode" &&
      currentUrl !== "/user/smsLogin" &&
      currentUrl !== "/wxMpLinkman/getOpenId" &&
      currentUrl !== "/wxMpLinkman/bindMobile" &&
      currentUrl !== "/wxMpLinkman/unbindMobile" &&
      currentUrl !== "/wxMpLinkman/getMobileByOpenId" &&
      currentUrl !== "/camera/get" &&
      currentUrl !== "/camera/login" &&
      currentUrl !== "/camera/info"
    ) {
      let token = asc.decrypt(sessionStorage.getItem("token"));
      config.headers.token = token;
    }
    return config;
  },
  (err) => Promise.reject(err)
);

// 响应拦截
axios.interceptors.response.use(
  (res) => {
    // console.log(res, "Err");
    // if (res.data.code == 20000) {
    //     return res.data;
    // } else
    if (res.data.code == 11137) {
      if (tokenLoseFlag == false) {
        tokenLoseFlag = true;
        Notification({
          title: "温馨提示",
          message: "账号已停用，请联系管理员",
          type: "error",
        });
        setTimeout(() => {
          sessionStorage.clear();
          router.push("/login");
          window.location.reload();
        }, 1000);
      }
    } else if (res.data.code == 10030) {
      if (tokenLoseFlag == false) {
        tokenLoseFlag = true;
        Notification({
          title: "温馨提示",
          message: "账号已停用，请联系管理员",
          type: "error",
        });
        setTimeout(() => {
          sessionStorage.clear();
          router.push("/login");
          window.location.reload();
        }, 1000);
      }
    } else {
      return res.data;
    }
  },
  (err) => {
    // console.log(err, "Err");
    let { data } = err.response;
    // console.log(err);
    switch (data.code) {
      case 20000:
        tokenLoseFlag = false;
        break;
      case 11112:
        if (tokenLoseFlag == false) {
          tokenLoseFlag = true;
          Notification({
            title: "温馨提示",
            message: "身份过期，请重新登录",
            type: "error",
          });
          setTimeout(() => {
            sessionStorage.clear();
            router.push("/login");
            window.location.reload();
          }, 1000);
        }
        break;
      case 11113:
        if (tokenLoseFlag == false) {
          tokenLoseFlag = true;
          Notification({
            title: "温馨提示",
            message: "登录过期，请重新登录",
            type: "error",
          });
          setTimeout(() => {
            sessionStorage.clear();
            router.push("/login");
            window.location.reload();
          }, 1000);
        }
        break;
      case 11114:
        if (tokenLoseFlag == false) {
          tokenLoseFlag = true;
          MessageBox.alert("账号已在另一台设备登录", "温馨提示", {
            confirmButtonText: "确定",
            callback: (action) => {
              setTimeout(() => {
                sessionStorage.clear();
                router.push("/login");
                window.location.reload();
              }, 500);
            },
          });
        }
        break;
      case 11115:
        if (tokenLoseFlag == false) {
          tokenLoseFlag = true;
          MessageBox.alert("账号已在另一台设备登录", "温馨提示", {
            confirmButtonText: "确定",
            callback: (action) => {
              setTimeout(() => {
                sessionStorage.clear();
                router.push("/login");
                window.location.reload();
              }, 500);
            },
          });
        }
        break;
      case 30001:
        if (tokenLoseFlag == false) {
          tokenLoseFlag = true;
          Notification({
            title: "温馨提示",
            message: data.message,
            type: "error",
          });
          setTimeout(() => {
            sessionStorage.clear();
            router.push("/login");
            window.location.reload();
          }, 1000);
        }
        break;
      case 11111:
        if (tokenLoseFlag == false) {
          tokenLoseFlag = true;
          Notification({
            title: "温馨提示",
            message: "身份过期,请重新登录",
            type: "error",
          });
          setTimeout(() => {
            sessionStorage.clear();
            router.push("/login");
            window.location.reload();
          }, 1000);
        }
        break;
      default:
        if (tokenLoseFlag == false) {
          return data;
          Notification({
            title: "温馨提示",
            message: data.message,
            type: "error",
          });
          break;
        }
    }
  }
);

// get请求
export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params,
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

// post请求
export function post(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then((res) => {
        // resolve(res.data)
        resolve(res);
      })
      .catch((err) => {
        reject(err); //失败
      });
  });
}
// delete请求，注：delete不能当做函数名，他是关键字
export function del(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios
      .delete(url, data)
      .then((res) => {
        resolve(res);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

// put请求
export function put(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .put(url, params)
      .then((res) => {
        resolve(res);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

// delete请求，注：delete不能当做函数名，他是关键字
export function del2(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios
      .delete(url, { data })
      .then((res) => {
        resolve(res);
      })
      .catch((error) => {
        reject(error);
      });
  });
}
